﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mobile_VTBL.Models;
using Mobile_VTBL.Models.DTO;

namespace Mobile_VTBL.Controllers
{
    public class ProductController : Controller
    {
        public const int PAGE_SIZE = 20;

        public ActionResult Detail(int ID)
        {
            using (var db = new DataContext())
            {
                var Product = db.Products.SingleOrDefault(x => x.ID == ID);

                return View(Product);
            }
        }

        public ActionResult Search(string key, int? Page)
        {
            using (var db = new DataContext())
            {
                var Products = db.Products.Where(x => x.Name.Contains(key)).Select(x => new ProductList { ID = x.ID, Images = x.Images, Name = x.Name }).OrderBy(x => x.ID).ToList();

                if (!Page.HasValue)
                    Page = 1;
                ViewBag.CurrentPage = Page;
                ViewBag.TotalPages = Products.Count / 20 + (Products.Count % 20 == 0 ? 0 : 1);
                ViewBag.ListProduct = Products.Skip((Page.Value - 1) * PAGE_SIZE).Take(PAGE_SIZE).ToList();

                return View();
            }
        }
    }
}
